<template>
  <div class="topic-list">
    <div class="page-header">
      <h2>论文题目管理</h2>
      <el-button type="primary" @click="handleAdd" v-if="isTeacher">
        <el-icon><Plus /></el-icon>发布题目
      </el-button>
    </div>

    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="题目">
          <el-input v-model="searchForm.title" placeholder="请输入题目关键词" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="topics" stripe v-loading="loading">
        <el-table-column prop="title" label="题目" show-overflow-tooltip />
        <el-table-column prop="teacher.user.real_name" label="指导教师" />
        <el-table-column prop="max_students" label="可选人数" width="100" />
        <el-table-column prop="current_students" label="已选人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleView(row)">
                查看
              </el-button>
              <el-button 
                type="primary" 
                link 
                @click="handleEdit(row)"
                v-if="isTeacher && row.teacher_id === currentUser.id"
              >
                编辑
              </el-button>
              <el-button 
                type="primary" 
                link 
                @click="handleDelete(row)"
                v-if="isTeacher && row.teacher_id === currentUser.id"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 题目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发布题目' : '编辑题目'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="题目" prop="title">
          <el-input v-model="form.title" placeholder="请输入题目" />
        </el-form-item>
        <el-form-item label="可选人数" prop="max_students">
          <el-input-number v-model="form.max_students" :min="1" :max="5" />
        </el-form-item>
        <el-form-item label="题目描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入题目描述"
          />
        </el-form-item>
        <el-form-item label="技术要求" prop="requirements">
          <el-input
            v-model="form.requirements"
            type="textarea"
            :rows="4"
            placeholder="请输入技术要求"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看题目对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="题目详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="题目">{{ currentTopic.title }}</el-descriptions-item>
        <el-descriptions-item label="指导教师">{{ currentTopic.teacher?.user?.real_name }}</el-descriptions-item>
        <el-descriptions-item label="可选人数">{{ currentTopic.max_students }}</el-descriptions-item>
        <el-descriptions-item label="已选人数">{{ currentTopic.current_students }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentTopic.status)">
            {{ getStatusText(currentTopic.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="题目描述">{{ currentTopic.description }}</el-descriptions-item>
        <el-descriptions-item label="技术要求">{{ currentTopic.requirements }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref(null)
const currentTopic = ref({})

const searchForm = reactive({
  title: '',
  status: ''
})

const form = reactive({
  title: '',
  max_students: 1,
  description: '',
  requirements: ''
})

const rules = {
  title: [
    { required: true, message: '请输入题目', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  max_students: [
    { required: true, message: '请选择可选人数', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入题目描述', trigger: 'blur' }
  ],
  requirements: [
    { required: true, message: '请输入技术要求', trigger: 'blur' }
  ]
}

const topics = ref([])
const currentUser = computed(() => JSON.parse(localStorage.getItem('user') || '{}'))
const isTeacher = computed(() => currentUser.value.role === 'teacher')

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

const fetchTopics = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      per_page: pageSize.value,
      ...searchForm
    })
    const response = await fetch(`/api/thesis-topics?${params}`)
    const data = await response.json()
    topics.value = data.data
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchTopics()
}

const resetSearch = () => {
  searchForm.title = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTopics()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTopics()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    title: '',
    max_students: 1,
    description: '',
    requirements: ''
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  currentTopic.value = row
  viewDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      type: 'warning'
    })
    
    const response = await fetch(`/api/thesis-topics/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.ok) {
      ElMessage.success('删除成功')
      fetchTopics()
    } else {
      const data = await response.json()
      ElMessage.error(data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const url = dialogType.value === 'add' 
      ? '/api/thesis-topics'
      : `/api/thesis-topics/${form.id}`
    
    const method = dialogType.value === 'add' ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(form)
    })
    
    const data = await response.json()
    
    if (response.ok) {
      ElMessage.success(dialogType.value === 'add' ? '发布成功' : '更新成功')
      dialogVisible.value = false
      fetchTopics()
    } else {
      ElMessage.error(data.message || (dialogType.value === 'add' ? '发布失败' : '更新失败'))
    }
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '发布失败' : '更新失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchTopics()
})
</script>

<style scoped>
.topic-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 